package com.stedu.mall.userservice.service;

import com.stedu.mall.common.bean.Addr;
import com.stedu.mall.common.exception.SteduException;
import com.stedu.mall.common.service.AddrService;
import com.stedu.mall.userservice.mapper.AddrMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@DubboService
public class AddrServiceImpl implements AddrService {
    @Autowired
    private AddrMapper addrMapper;

    @Override
    public boolean insert(Addr addr) throws SteduException {
        if (!addrMapper.selectByCondition(addr).isEmpty()) {
            throw new SteduException("该地址已存在，无法添加");
        }
        addr.setStatus(0);
        return addrMapper.insert(addr) == 1;
    }

    @Override
    public boolean delete(Integer id, Integer userId) throws SteduException {
        //判断地址是否存在
        Addr addr = addrMapper.selectById(id);
        if (addr == null) {
            throw new SteduException("该地址不存在，无法删除");
        }
        //判断是否属于当前的用户
        if (!addr.getUserId().equals(userId)) {
            throw new SteduException("该地址属于其他用户，无法删除");
        }
        //删除
        return addrMapper.delete(id) == 1;
    }

    @Override
    public boolean update(Addr addr, Integer userId) throws SteduException {
        //判断地址是否存在
        Addr a = addrMapper.selectById(addr.getId());
        if (a == null) {
            throw new SteduException("该地址不存在，无法修改");
        }
        //判断是否属于当前的用户
        if (!a.getUserId().equals(userId)) {
            throw new SteduException("该地址属于其他用户，无法修改");
        }
        /*
         * 设置为默认地址的处理
         * 之前的默认地址设置为普通地址
         * */
        if (addr.getStatus().equals(1)) {
            //查出当前的默认地址
            Addr condition = new Addr();
            condition.setStatus(1);
            condition.setUserId(userId);
            List<Addr> addrList = addrMapper.selectByCondition(condition);
            if (!addrList.isEmpty()) {
                //将当前地址设为普通地址
                Addr addr1 = new Addr();
                addr1.setId(addrList.get(0).getId());
                addr1.setStatus(0);
                addrMapper.update(addr1);
            }
        }
        return addrMapper.update(addr) == 1;
    }

    @Override
    public List<Addr> selectByCondition(Addr condition) {
        return addrMapper.selectByCondition(condition);
    }

    @Override
    public Addr selectById(Integer id) {
        return addrMapper.selectById(id);
    }
}
